import {
  login,
  logout,
  getInfo
} from '@/api/user'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'
import router, {
  resetRouter
} from '@/router'
import {
  getBackLoginToken,
  getUserLoginToken
} from "@/api/login";

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  id: '',
  authState: '',
  deliverNum: 0,
  shipmentTipsNum: 0,
  systemTime: 0,
  siteId: 'MX',
  authUrl: '', // 授权的跳转链接
  cbtAuthUrl: '', // CBT授权链接
  isFinishAuth: false,
  platformNum: 1, // 授权的平台数量
  defaultAccountTypeNum: 1, // 默认平台的选项
  accountMKD: false, // 是否授权了美客多店铺
  accountFalabella: false, // 是否授权了falabella平台
  accountAmazon: false, // 是否授权了amazon平台
  accountShopee: false, // 是否授权了虾皮平台
  accountShein: false, // 是否授权了希音平台
  accountTikTok: false, // 是否授权了抖音平台
  accountAliexpress: false, // 是否授权了速卖通平台
  SPAuthUrl: '', // 虾皮的授权链接
  amount: 0, // 用户金额
  middleWorkNum: 1, // 送仓工单数量
  transferWorkNum: 1, // 调货工单数量
  labelOrderNum: 1, // 贴标工单数量
  shipmentTableType: 1, // 货件类型 1混箱和整形 仅整箱
  payPageType: 'SKIP', // 支付页面类型 SKIP: 跳转  POP: 弹框
  isNoticeSetting: false,
  handlingChargeStatus: 1, // 是否加收手续费 1加收 2免收
  wechatPayCommissionPercentage: 0.009, // 微信手续费收费率
  AliPayCommissionPercentage: 0.006, // 支付宝手续费收费率
  RemittanceCommissionPercentage: 0, // 汇款手续费收费率
  remittanceAccount: [], // 汇款账号列表
  rechargeNotArrivedNum: 0, // 汇款账号列表
  isAuthMKDCBT: false, // 是否授权了美客多店铺
  userPackageMaterial: [], // 用户包材列表
  warehouseName: '', // 仓库名
  localTime: '',
  // 库存预警
  goodsTipsNum: 0,
  // 是否隐藏充值按钮
  isHiddenPay: false,
  // 是否隐藏独立站授权按钮
  isHiddenPacketButton: false,
  router: {},

  currentTimezone: '',
  //是否显示日志
  isShowLog:1
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  ROLE_TYPE: (state, roleType) => {
    state.roleType = roleType
  },

  SET_ID: (state, id) => {
    state.id = id
  },
  SET_IS_SHOW_LOG: (state, isShowLog) => {
    state.isShowLog = isShowLog
  },
  SET_AUTH_STATE: (state, authState) => {
    state.authState = authState
  },
  SET_DELIVER_NUM: (state, deliverNum) => {
    state.deliverNum = deliverNum
  },
  SET_SHIPMENT_TIPS_NUM: (state, shipmentTipsNum) => {
    state.shipmentTipsNum = shipmentTipsNum
  },
  SET_SYSTEM_TIME: (state, systemTime) => {
    state.systemTime = systemTime
  },
  SET_AUTH_URL: (state, authUrl) => {
    state.authUrl = authUrl
  },
  SET_CBT_AUTH_URL: (state, cbtAuthUrl) => {
    state.cbtAuthUrl = cbtAuthUrl
  },
  SET_SITE_ID: (state, siteId) => {
    state.siteId = siteId
  },
  SET_IS_FINISH: (state, isFinishAuth) => {
    state.isFinishAuth = isFinishAuth
  },
  SET_PLATFORM_NUM: (state, platformNum) => {
    state.platformNum = platformNum
  },
  SET_DEFAULT_ACCOUNT_TYPE_NUM: (state, defaultAccountTypeNum) => {
    state.defaultAccountTypeNum = defaultAccountTypeNum
  },
  SET_ACCOUNT_MKD: (state, accountMKD) => {
    state.accountMKD = accountMKD
  },
  SET_ACCOUNT_FALABELLA: (state, accountFalabella) => {
    state.accountFalabella = accountFalabella
  },
  SET_ACCOUNT_AMAZON: (state, accountAmazon) => {
    state.accountAmazon = accountAmazon
  },
  SET_ACCOUNT_SHOPEE: (state, accountShopee) => {
    state.accountShopee = accountShopee
  },
  SET_ACCOUNT_SHEIN: (state, accountShein) => {
    state.accountShein = accountShein
  },
  SET_ACCOUNT_TIKTOK: (state, accountTikTok) => {
    state.accountTikTok = accountTikTok
  },
  SET_ACCOUNT_ALIEXPRESS: (state, accountAliexpress) => {
    state.accountAliexpress = accountAliexpress
  },
  SET_SP_AUTH_URL: (state, SPAuthUrl) => {
    state.SPAuthUrl = SPAuthUrl
  },
  SET_AMOUNT: (state, amount) => {
    state.amount = amount
  },
  SET_MIDDLE_WORK_NUM: (state, middleWorkNum) => {
    state.middleWorkNum = middleWorkNum
  },
  SET_TRANSFER_WORK_NUM: (state, transferWorkNum) => {
    state.transferWorkNum = transferWorkNum
  },
  SET_LABEL_ORDER_NUM: (state, labelOrderNum) => {
    state.labelOrderNum = labelOrderNum
  },
  SET_SHIPMENT_TABLE_TYPE: (state, shipmentTableType) => {
    state.shipmentTableType = shipmentTableType
  },
  SET_PAY_PAGE_TYPE: (state, payPageType) => {
    state.payPageType = payPageType
  },
  SET_IS_NOTICE_SETTING: (state, isNoticeSetting) => {
    state.isNoticeSetting = isNoticeSetting
  },
  SET_HANDLING_CHARGE_STATUS: (state, handlingChargeStatus) => {
    state.handlingChargeStatus = handlingChargeStatus
  },
  SET_WECHAT_PAY_COMMISSION_PERCENTAGE: (state, wechatPayCommissionPercentage) => {
    state.wechatPayCommissionPercentage = wechatPayCommissionPercentage
  },
  SET_ALI_PAY_COMMISSION_PERCENTAGE: (state, AliPayCommissionPercentage) => {
    state.AliPayCommissionPercentage = AliPayCommissionPercentage
  },
  SET_REMITTANCE_COMMISSION_PERCENTAGE: (state, RemittanceCommissionPercentage) => {
    state.RemittanceCommissionPercentage = RemittanceCommissionPercentage
  },
  SET_REMITTANCE_ACCOUNT: (state, remittanceAccount) => {
    state.remittanceAccount = remittanceAccount
  },
  SET_RECHARGE_NOT_ARRIVED_NUM: (state, rechargeNotArrivedNum) => {
    state.rechargeNotArrivedNum = rechargeNotArrivedNum
  },
  SET_IS_AUTH_MKD_AUTH: (state, isAuthMKDCBT) => {
    state.isAuthMKDCBT = isAuthMKDCBT
  },
  SET_USER_PACKAGE_MATERIAL: (state, userPackageMaterial) => {
    state.userPackageMaterial = userPackageMaterial
  },
  SET_INFO: (state, info) => {
    state.warehouseName = info.warehouseName
    state.localTime = info.localTime
    state.router = info.router
  },
  SET_GOODS_TIPS_NUM: (state, goodsTipsNum) => {
    state.goodsTipsNum = goodsTipsNum
  },
  SET_IS_HIDDEN_PAY: (state, isHiddenPay) => {
    state.isHiddenPay = isHiddenPay
  },
  SET_IS_HIDDEN_PACKET_BUTTON: (state, isHiddenPacketButton) => {
    state.isHiddenPacketButton = isHiddenPacketButton
  },
}

const actions = {
  // user login
  login({
    commit
  }, userInfo) {
    // const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login(userInfo).then(res => {
        const {
          data,
          info
        } = res
        if (res.error === 0) {
          commit('SET_TOKEN', info.token)
          setToken(info.token)
          resolve()
        } else {
          reject(res)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(res => {
        const {
          data,
          info
        } = res
        if (!data.id) {
          reject('Verification failed, please Login again.')
        }

        // const { roles, name, avatar, introduction } = data

        // roles must be a non-empty array
        /*if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }*/

        // const roles = [data.accountType];
        // 用户角色
        let roles = []; //

        if (!data.roles) {
          roles = ['admin']
        } else {
          if (data.roles == 'commissioner') {

            roles = data.roleType
          } else {

            roles = [data.roles]
          }
        }
        const name = data.account;
        const avatar = data.avatar || '';
        const introduction = '';

        commit('ROLE_TYPE', data.roles)
        commit('SET_ID', data.id)
        commit('SET_IS_SHOW_LOG', info.isShowLog)

        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        commit('SET_DELIVER_NUM', info.deliverNum)
        commit('SET_SHIPMENT_TIPS_NUM', info.shipmentTipsNum)
        commit('SET_SYSTEM_TIME', new Date(info.localTime).getTime())
        commit('SET_PLATFORM_NUM', info.platformNum)
        commit('SET_ACCOUNT_MKD', info.accountMKD >= 1)
        commit('SET_ACCOUNT_FALABELLA', info.accountFalabella >= 1)
        commit('SET_ACCOUNT_AMAZON', info.accountAmazon >= 1)
        commit('SET_ACCOUNT_SHOPEE', info.accountShopee >= 1)
        commit('SET_ACCOUNT_SHEIN', info.accountShein >= 1)
        commit('SET_ACCOUNT_TIKTOK', info.accountTikTok >= 1)
        commit('SET_ACCOUNT_ALIEXPRESS', info.accountAliexpress > 0)

        let defaultAccountTypeNum = 1;
        if (info.accountMKD >= 1) {
          defaultAccountTypeNum = 1;
        } else if (info.accountFalabella >= 1) {
          defaultAccountTypeNum = 2;
        } else if (info.accountShopee >= 1) {
          defaultAccountTypeNum = 3;
        } else if (info.accountShein >= 1) {
          defaultAccountTypeNum = 4;
        } else if (info.accountAmazon >= 1) {
          defaultAccountTypeNum = 5;
        } else if (info.accountTikTok >= 1) {
          defaultAccountTypeNum = 6;
        } else if (info.accountAliexpress >= 1) {
          defaultAccountTypeNum = 8;
        }
        commit('SET_DEFAULT_ACCOUNT_TYPE_NUM', defaultAccountTypeNum)



        // 美客多授权的state参数
        commit('SET_AUTH_STATE', data.authState)

        commit('SET_AUTH_URL', data.authUrl)
        commit('SET_CBT_AUTH_URL', data.cbtAuthUrl)
        commit('SET_SP_AUTH_URL', data.SPAuthUrl)
        commit('SET_SITE_ID', data.siteId)
        commit('SET_IS_AUTH_MKD_AUTH', info.isAuthMKDCBT)

        commit('SET_IS_FINISH', data.isFinishAuth)
        commit('SET_AMOUNT', data.amount)
        commit('SET_IS_NOTICE_SETTING', data.isNoticeSetting)

        commit('SET_MIDDLE_WORK_NUM', info.middleWorkNum)
        commit('SET_TRANSFER_WORK_NUM', info.transferWorkNum)
        commit('SET_LABEL_ORDER_NUM', info.labelOrderNum)

        commit('SET_SHIPMENT_TABLE_TYPE', info.shipmentTableType)
        commit('SET_PAY_PAGE_TYPE', info.payPageType)
        commit('SET_HANDLING_CHARGE_STATUS', info.handlingChargeStatus)
        commit('SET_WECHAT_PAY_COMMISSION_PERCENTAGE', info.wechatPayCommissionPercentage)
        commit('SET_ALI_PAY_COMMISSION_PERCENTAGE', info.AliPayCommissionPercentage)
        commit('SET_REMITTANCE_COMMISSION_PERCENTAGE', info.RemittanceCommissionPercentage)
        commit('SET_REMITTANCE_ACCOUNT', info.remittanceAccount)
        commit('SET_RECHARGE_NOT_ARRIVED_NUM', info.rechargeNotArrivedNum)
        commit('SET_USER_PACKAGE_MATERIAL', info.userPackageMaterial)
        commit('SET_GOODS_TIPS_NUM', info.goodsTipsNum)
        commit('SET_IS_HIDDEN_PAY', info.isHiddenPay)
        commit('SET_IS_HIDDEN_PACKET_BUTTON', info.isHiddenPacketButton)

        commit('SET_INFO', info)

        resolve({
          roles,
          name,
          avatar,
          introduction
        })
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({
    commit,
    state,
    dispatch
  }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, {
          root: true
        })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({
    commit
  }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({
    commit,
    dispatch
  }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const {
      roles
    } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, {
      root: true
    })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, {
      root: true
    })
  },

  // 后台登录
  adminLogin({
    commit
  }, key) {
    return new Promise((resolve, reject) => {
      getUserLoginToken(key)
        .then(res => {
          const {
            info
          } = res
          if (res.error === 0) {
            commit('SET_TOKEN', info.token)
            setToken(info.token)
            resolve()
          } else {
            reject(res)
          }
        }).catch(error => {
          reject(error)
        })
    })
  },
  // 演示登录
  backLogin({
    commit
  }, key) {
    return new Promise((resolve, reject) => {
      getBackLoginToken(key)
        .then(res => {
          const {
            info
          } = res
          if (res.error === 0) {
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            removeToken()
            resetRouter()
            commit('SET_TOKEN', info.token)
            setToken(info.token)
            resolve()
          } else {
            reject(res)
          }
        }).catch(error => {
          reject(error)
        })
    })
  },

  // 更改时间
  setSystemTime({
    commit
  }, time) {
    commit('SET_SYSTEM_TIME', time)
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
